import { apiClient } from './index'
import { mockApi } from '@/utils/mockApi'
import type { 
  Report, 
  ReportTemplate,
  ApiResponse,
  PaginationResponse,
  QueryParams 
} from '@/types'

export const reportApi = {
  // 获取报表列表
  getReports: async (params?: QueryParams): Promise<ApiResponse<PaginationResponse<Report>>> => {
    // 模拟数据
    const mockReports: Report[] = [
      {
        id: 1,
        name: '数据层概览报表',
        description: '各数据层统计报表',
        report_type: 'table',
        query_sql: 'SELECT layer, COUNT(*) as table_count FROM monitored_tables GROUP BY layer',
        parameters: {},
        schedule_config: {
          frequency: 'daily',
          time: '09:00:00'
        },
        template_id: 1,
        wechat_bot_id: 1,
        is_active: true,
        created_by: 1,
        created_at: '2024-01-01T00:00:00Z',
        updated_at: '2024-01-01T00:00:00Z',
        output_format: 'CSV'
      },
      {
        id: 2,
        name: 'Flink作业状态报表',
        description: 'Flink作业运行状态统计',
        report_type: 'table',
        query_sql: 'SELECT status, COUNT(*) as job_count FROM flink_jobs GROUP BY status',
        parameters: {},
        schedule_config: {
          frequency: 'hourly',
          time: '00:00:00'
        },
        template_id: 2,
        wechat_bot_id: 1,
        is_active: true,
        created_by: 1,
        created_at: '2024-01-01T00:00:00Z',
        updated_at: '2024-01-01T00:00:00Z',
        output_format: 'EXCEL'
      }
    ]
    
    return {
      code: 200,
      message: 'success',
      data: {
        items: mockReports,
        pagination: {
          page: 1,
          size: 20,
          total: mockReports.length,
          pages: 1
        }
      },
      timestamp: new Date().toISOString()
    }
  },

  // 获取报表详情
  getReportDetail: async (reportId: number): Promise<ApiResponse<Report>> => {
    return {
      code: 200,
      message: 'success',
      data: {} as Report,
      timestamp: new Date().toISOString()
    }
  },

  // 创建报表
  createReport: async (data: Partial<Report>): Promise<ApiResponse<Report>> => {
    return {
      code: 200,
      message: 'success',
      data: data as Report,
      timestamp: new Date().toISOString()
    }
  },

  // 更新报表
  updateReport: async (reportId: number, data: Partial<Report>): Promise<ApiResponse<Report>> => {
    return {
      code: 200,
      message: 'success',
      data: data as Report,
      timestamp: new Date().toISOString()
    }
  },

  // 删除报表
  deleteReport: async (reportId: number): Promise<ApiResponse<void>> => {
    return {
      code: 200,
      message: 'success',
      data: undefined,
      timestamp: new Date().toISOString()
    }
  },

  // 执行报表
  executeReport: async (reportId: number): Promise<ApiResponse<void>> => {
    return {
      code: 200,
      message: 'success',
      data: undefined,
      timestamp: new Date().toISOString()
    }
  },

  // 预览报表（新增）
  previewReport: async (reportId: number, format: import('@/types').ReportOutputFormat): Promise<ApiResponse<any>> => {
    // 模拟不同格式预览
    const baseRows = [
      { id: 1, name: 'Alice', amount: 123.45 },
      { id: 2, name: 'Bob', amount: 67.89 },
      { id: 3, name: 'Carol', amount: 10.2 }
    ]
    if (format === 'CSV') {
      const header = 'id,name,amount\n'
      const body = baseRows.map(r => `${r.id},${r.name},${r.amount}`).join('\n')
      return { code: 200, message: 'success', data: header + body, timestamp: new Date().toISOString() }
    }
    if (format === 'HTML') {
      const rows = baseRows.map(r => `<tr><td>${r.id}</td><td>${r.name}</td><td>${r.amount}</td></tr>`).join('')
      const html = `<!DOCTYPE html><html><head><meta charset="utf-8"><title>预览</title></head><body><table border="1"><thead><tr><th>id</th><th>name</th><th>amount</th></tr></thead><tbody>${rows}</tbody></table></body></html>`
      return { code: 200, message: 'success', data: html, timestamp: new Date().toISOString() }
    }
    if (format === 'JSON') {
      return { code: 200, message: 'success', data: baseRows, timestamp: new Date().toISOString() }
    }
    if (format === 'EXCEL') {
      // excel 预览：返回二维数组示例，前端以表格方式渲染
      const data = [['id','name','amount'], ...baseRows.map(r => [r.id, r.name, r.amount])]
      return { code: 200, message: 'success', data, timestamp: new Date().toISOString() }
    }
    return { code: 400, message: 'unsupported format', data: null, timestamp: new Date().toISOString() }
  },

  // 获取报表模板
  getTemplates: async (): Promise<ApiResponse<PaginationResponse<ReportTemplate>>> => {
    return mockApi.report.getTemplates()
  },

  // 新增：获取报表执行历史
  getExecutions: async (params?: QueryParams): Promise<ApiResponse<PaginationResponse<import('@/types').ReportExecution>>> => {
    const now = Date.now()
    const mock = Array.from({ length: 12 }).map((_, i) => {
      const start = new Date(now - i * 3600_000)
      const duration = Math.floor(Math.random() * 30000) + 2000
      const statusPool = ['SUCCEEDED','FAILED','RUNNING'] as const
      const status = statusPool[i % statusPool.length]
      return {
        id: i + 1,
        report_id: i % 2 === 0 ? 1 : 2,
        report_name: i % 2 === 0 ? '数据层概览报表' : 'Flink作业状态报表',
        status,
        started_at: start.toISOString(),
        finished_at: status === 'RUNNING' ? undefined : new Date(start.getTime() + duration).toISOString(),
        duration_ms: status === 'RUNNING' ? undefined : duration,
        row_count: status === 'SUCCEEDED' ? Math.floor(Math.random() * 10000) : undefined,
        output_format: 'CSV' as const,
        output_uri: status === 'SUCCEEDED' ? `https://example.com/report/${i+1}.csv` : undefined,
        error_message: status === 'FAILED' ? '执行失败：SQL语法错误' : undefined,
        created_at: start.toISOString(),
        updated_at: new Date().toISOString()
      }
    })

    return {
      code: 200,
      message: 'success',
      data: {
        items: mock,
        pagination: { page: 1, size: mock.length, total: mock.length, pages: 1 }
      },
      timestamp: new Date().toISOString()
    }
  }
} 